<template>
  <div class="dx-swatch-additional side-navigation-menu" @click="forwardClick">
    <slot />
    <div class="menu-container">
      <dx-tree-view
        ref="treeViewRef"
        :items="items"
        key-expr="path"
        selection-mode="single"
        :focus-state-enabled="false"
        expand-event="click"
        @item-click="handleItemClick"
        width="100%"
      />
    </div>
  </div>
</template>

<script lang="ts">
import DxTreeView from "devextreme-vue/ui/tree-view";
import { ApiTool } from "../api/api-tool";
import Menu from "../utils/menu";
import { Options, Vue } from "vue-class-component";
import { Inject, Prop, Ref, Watch } from "vue-property-decorator";
import { ApiExceptionShow } from "../utils/api-exception-show";
import { navigationList } from "../app-navigation";
@Options({
  components: {
    DxTreeView,
  },
})
export default class SideNavMenu extends Vue {
  @Prop()
  compactMode: boolean;

  @Ref()
  treeViewRef: DxTreeView;

  @Inject()
  apiTool: ApiTool;

  @Inject()
  menu: Menu;

  items = [];

  forwardClick(...args) {
    this.$emit("click", args);
  }

  handleItemClick(e) {
    if (!e.itemData.path || this.compactMode) {
      return;
    }
    let item = e.itemData;
    if (item.type == "www") {
      window.open(item.path);
    } else {
      this.$router.push(e.itemData.path);
    }
    console.log(e);
    const pointerEvent = e.event;
    pointerEvent.stopPropagation();
  }

  updateSelection() {
    if (!this.treeViewRef || !this.treeViewRef.instance) {
      return;
    }
    this.treeViewRef.instance.selectItem(this.$route.path);
    this.treeViewRef.instance.expandItem(this.$route.path);
  }

  @Watch("compactMode")
  watchCompactMode(v: boolean) {
    if (v) {
      this.treeViewRef.instance.collapseAll();
    } else {
      this.updateSelection();
    }
  }

  @Watch("$route.path")
  watchRoutePath() {
    this.updateSelection();
  }

  private selectedNode(items: any[]) {
    if (!items) return false;
    for (let item of items) {
      if (item.path == this.$route.path) {
        item.selected = true;
        return true;
      }
      if (this.selectedNode(item.items)) {
        item.expanded = true;
        return true;
      }
    }
    return false;
  }

  mounted() {
    this.menu.freshMenu(this.apiTool);
    let items = this.menu.getNavigation();
    this.selectedNode(items);
    this.items = items;
    if (this.compactMode) {
      this.treeViewRef.instance.collapseAll();
    }
  }
}
</script>

<style src="./side-nav-menu.scss" lang="scss"></style>
